package pain;

public class Test_2 {
    public static void main(String[] args) {
        int []arr={234,5,14,624,134,2456,234,654213,685,1354,8976,345,12};
        BBB.mergesort(arr,0,arr.length-1);
        for(int data:arr){
            System.out.print(data+" ");
        }

    }
}
class BBB{
    public static void mergesort(int []arr,int left,int right){
        if(left==right){
            return;
        }
        int mid=(left+right)/2;
        //分治
        mergesort(arr,left,mid);
        mergesort(arr,mid+1,right);

        //合并
        merge(arr,left,right,mid);
    }

    public static void merge(int[]arr,int left,int right,int mid){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        //创建临时数组
        int[] temarr=new int[right-left+1];
        int k=0;//记录临时数组元素下标
        while(s1<=e1&&s2<=e2){
            if(arr[s1]<=arr[s2]){
                temarr[k++]=arr[s1++];
            }
            else{
                temarr[k++]=arr[s2++];
            }
        }
        //保证每个数组
        while(s1<=e1){
            temarr[k++]=arr[s1++];
        }

        while(s2<=e2){
            temarr[k++]=arr[s2++];
        }
        //将临时数组元素传给数组
        for(int i=0;i<temarr.length;i++){
            arr[i+left]=temarr[i];
        }
    }
}
